!function () {
	var setting = {
		view: {showIcon: false},
		async: {enable: true, url: '/menu/findAllMenu'},
		check: {enable: true, chkboxType: {'Y': 'ps', 'N': 's'}},
		data: {simpleData: {enable: true, idKey: 'menuCode', pIdKey: 'parentCode', rootPId: 0}, key: {name: 'menuName',}},
		callback: {
			onAsyncSuccess: function (event, treeId) {
				var zTree = $.fn.zTree.getZTreeObj(treeId);
				var homeNode = zTree.getNodes()[0];
				homeNode.checked = true;
				homeNode.chkDisabled = true;
				zTree.updateNode(homeNode);
			}
		}
	};
	var zTree = $.fn.zTree.init($('#menuTree'), setting);

	layui.config({base: '/layui/lay/modules/'}).use(['table', 'laydate', 'dateformat', 'form','common'], function () {
		var $ = layui.jquery,
			table = layui.table,
			dateformat = layui.dateformat,
			common = layui.common,//自定义模块
			form = layui.form;
		// 表格渲染
		var tableIns = table.render({
			elem: '#roleTable',
			url: '/role/findRolePage',
			request: {pageName: 'pageNum', limitName: 'pageSize'},
			width: 1200,
			cols: [[
				/*{type: 'checkbox', fixed: 'left'},*/
				{field: 'roleId', title: 'ID', width: 80},
				{field: 'roleName', title: '角色名称', width: 160},
				{field: 'roleDescribe', title: '角色描述'},
				{
					field: 'status', title: '状态', width: 120, templet: function (row) {
						return row.status == 1 ? '启用' : '禁用';
					}
				},
				{
					field: 'createTime', title: '创建时间', width: 165, templet: function (row) {
						return dateformat.format(common.NewDate(row.createTime), 'yyyy-MM-dd hh:mm:ss');
					}
				},
				{
					field: 'updateTime', title: '修改时间', width: 165, templet: function (row) {
						return dateformat.format(common.NewDate(row.updateTime), 'yyyy-MM-dd hh:mm:ss');
					}
				},
				{fixed: 'right', title: '操作', toolbar: '#actionTool', width: 130, align: 'center'}
			]], page: true
		});
		// 搜索表格数据
		$('#renderTable').on('click', function () {
			table.reload('roleTable', {where: {roleName: $('#queryName').val()},page: {curr: 1}});
		});


        //自定义验证规则
        form.verify({
            roleName: function(value){
                if(value.length < 2 || value.length >16){
                    return '角色名称必须输入2-16个字符';
                }
            }
            ,roleDescribe:function (value) {
                if(value.length > 300 ){
                    return '角色描述最多只能输入300个字符';
                }
            }
        });

        // 添加按钮点击事件
        $('#addNew').on('click',function () {
            addRolo();
        });

        // 重置点击事件
        $('#resetSearch').click(function () {
            $('#queryTools input').val('');
            $('#queryTools select').val('');
            table.reload('roleTable', {where: {roleName: $('#queryName').val()},page: {curr: 1}});
        });

		// 监听行按钮事件
		table.on('tool(roleFilter)', function (obj) {
			var data = obj.data;
			if (obj.event === 'edit') {
				editRole(data.roleId);
				return false;
			} else if (obj.event === 'disable') {
				layer.confirm('确认禁用"' + data.roleName + '"吗？', {icon: 3, title: '警告！'}, function () {
					setStatus(data.roleId, 2);
				});
			} else if (obj.event === 'enable') {
				layer.confirm('确认启用"' + data.roleName + '"吗？', function () {
					setStatus(data.roleId, 1);
				});
			}
		});
		// 表单验证
		form.on('submit(editRole)', function (data) {
			var nodes = zTree.getCheckedNodes(true), menuIds = [1];
            if( nodes.length ==0 ){
                layer.msg("请选择角色权限");
                return false;
			}
			for (var i = 0; i < nodes.length; i++)
				menuIds.push(nodes[i].menuId);

			data.field['menuIds'] = menuIds;
			var postUrl = !data.field['roleId'] ? '/role/addNewRole' : '/role/editInfo';
			$.ajax({
				async: false, type: 'post', traditional: true, data: data.field, url: postUrl,
				success: function (data) {
					if (data && data.code == 200) {
						layer.closeAll();
						layer.alert('操作成功！', {icon: 1, title: '提示'});
                        table.reload('roleTable', {where: {"roleName":$('#queryName').val()}});
					} else
						layer.alert(data.msg || '操作失败了！', {icon: 5, title: '提示'});
				},
				error: function () {
					layer.closeAll();
					layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
				}
			});
			return false;
		});


        /***
		 * 新增角色
         */
		function addRolo(){
            $('input[name=status]:first').click();
            form.render('radio').val('roleForm', {roleId: '', roleName: '', roleDescribe: ''});
            zTree.checkAllNodes(false);
            layer.open({
                type: 1, maxmin: true, title: '添加角色', shade: 0.4, shadeClose: false,
                area: ['452px', '550px'], content: $('#roleForm').show(), btn: ['保存', '取消'],
                yes: function () {
                    $('#saveRole').click();
                }, btn2: function () {
                    layer.closeAll();
                }, end: function () {
                    $('#roleForm').hide();
                }
            });
		}

		// 修改状态
		function setStatus(roleIds, status) {
			$.ajax({
				async: false,
				type: 'post',
				traditional: true,
				url: '/role/setStatus',
				data: {roleIds: roleIds, status: status},
				success: function (data) {
					if (data && data.code == 200) {
						layer.alert('操作成功！', {icon: 1, title: '提示'});
						var page = tableIns.config.page, query = $('#queryName').val();
						table.reload('roleTable', {where: {pageNum: page.curr, pageSize: page.limit, roleName: query}});
					} else
						layer.alert(data.msg || '操作失败了！', {icon: 5, title: '提示'});
				},
				error: function () {
					layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
				}
			});
		}

		// 编辑角色
		function editRole(roleId) {
			$.ajax({
				async: false,
				url: '/role/editInfo?roleId=' + roleId,
				success: function (result) {
					if (result && result.code == 200) {
						var data = result.data, roleMenu = data.roleMenu;
						$('input[name=status]').eq(data.roleInfo.status - 1).click();
						form.render('radio').val('roleForm', {
							roleId: data.roleInfo.roleId,
							roleName: data.roleInfo.roleName,
							roleDescribe: data.roleInfo.roleDescribe,
						});
						zTree.checkAllNodes(false);
						for (var i = 0; i < roleMenu.length; i++) {
							zTree.checkNode(zTree.getNodeByParam('menuId', roleMenu[i].menuId), true, false);
						}
						layer.open({
							type: 1, maxmin: true, title: '编辑角色', shade: 0.4, shadeClose: false,
							area: ['452px', '550px'], content: $('#roleForm').show(), btn: ['保存', '取消'],
							yes: function () {
								$('#saveRole').click();
							},
							btn2: function () {
								layer.closeAll();
							},
							end: function () {
								$('#roleForm').hide();
							}
						});
					} else
						layer.alert(result.msg || '请求失败了！', {icon: 5, title: '提示'});
				},
				error: function () {
					layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
				}
			});
		}
	});
}();